package com.fangs.yehwangglobal.utils;

import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.ColorInt;
import androidx.annotation.DrawableRes;
import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
import androidx.core.view.ViewCompat;
import androidx.core.widget.TextViewCompat;

import com.fangs.yehwangglobal.base.YehApp;

/**
 *     desc  : 吐司相关工具类
 */
public final class ToastUtils {

    private static final int COLOR_DEFAULT = 0xFEFFFFFF;
    private static final Handler HANDLER = new Handler(Looper.getMainLooper());

    private static Toast sToast;
    private static int gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
    private static int xOffset = 0;
    private static int yOffset = (int) (64 * YehApp.getInstance().getResources().getDisplayMetrics().density + 0.5);
    private static int bgColor = 0xFF444444;//默认给当前项目的toast设置该颜色
    private static int bgResource = -1;
    private static int msgColor = COLOR_DEFAULT;

    private ToastUtils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * 设置吐司位置
     *
     * @param gravity 位置
     * @param xOffset x 偏移
     * @param yOffset y 偏移
     */
    public static void setGravity(final int gravity, final int xOffset, final int yOffset) {
        ToastUtils.gravity = gravity;
        ToastUtils.xOffset = xOffset;
        ToastUtils.yOffset = yOffset;
    }

    /**
     * 设置背景颜色
     *
     * @param backgroundColor 背景色
     */
    public static void setBgColor(@ColorInt final int backgroundColor) {
        ToastUtils.bgColor = backgroundColor;
    }

    /**
     * 设置背景资源
     *
     * @param bgResource 背景资源
     */
    public static void setBgResource(@DrawableRes final int bgResource) {
        ToastUtils.bgResource = bgResource;
    }

    /**
     * 设置消息颜色
     *
     * @param msgColor 颜色
     */
    public static void setMsgColor(@ColorInt final int msgColor) {
        ToastUtils.msgColor = msgColor;
    }

    /**
     * 安全地显示短时吐司
     *
     * @param text 文本
     */
    public static void showShort(@NonNull final CharSequence text) {
        show(text, Toast.LENGTH_SHORT);
    }

    /**
     * 安全地显示短时吐司
     *
     * @param resId 资源 Id
     */
    public static void showShort(@StringRes final int resId) {
        show(resId, Toast.LENGTH_SHORT);
    }

    /**
     * 安全地显示短时吐司
     *
     * @param resId 资源 Id
     * @param args  参数
     */
    public static void showShort(@StringRes final int resId, final Object... args) {
        show(resId, Toast.LENGTH_SHORT, args);
    }

    /**
     * 安全地显示短时吐司
     *
     * @param format 格式
     * @param args   参数
     */
    public static void showShort(final String format, final Object... args) {
        show(format, Toast.LENGTH_SHORT, args);
    }

    /**
     * 安全地显示长时吐司
     *
     * @param text 文本
     */
    public static void showLong(@NonNull final CharSequence text) {
        show(text, Toast.LENGTH_LONG);
    }

    /**
     * 安全地显示长时吐司
     *
     * @param resId 资源 Id
     */
    public static void showLong(@StringRes final int resId) {
        show(resId, Toast.LENGTH_LONG);
    }

    /**
     * 安全地显示长时吐司
     *
     * @param resId 资源 Id
     * @param args  参数
     */
    public static void showLong(@StringRes final int resId, final Object... args) {
        show(resId, Toast.LENGTH_LONG, args);
    }

    /**
     * 安全地显示长时吐司
     *
     * @param format 格式
     * @param args   参数
     */
    public static void showLong(final String format, final Object... args) {
        show(format, Toast.LENGTH_LONG, args);
    }

    /**
     * 安全地显示短时自定义吐司
     */
    public static void showCustomShort(@LayoutRes final int layoutId, @IdRes final int textId, String msg) {
        View view = getView(layoutId);
        if (view == null) return;

        TextView tv = view.findViewById(textId);
        if (tv != null) {
            tv.setText(msg);
            /**
             * 此处用于接口返回提示文字超长时 动态修改提示框的宽度 避免提示过于狭长难看
             */
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tv.getLayoutParams();
            if (msg.length() > 104) {
                params.width = DisplayUtils.dip2px(YehApp.getInstance(), 300f);
            } else {
                params.width = DisplayUtils.dip2px(YehApp.getInstance(), 160f);
            }
            tv.setLayoutParams(params);
        }
        show(view, Toast.LENGTH_SHORT);
    }

    /**
     * 安全地显示短时自定义吐司
     */
    public static void showCustomShort(@LayoutRes final int layoutId, @IdRes final int textId, @StringRes final int resId) {
        View view = getView(layoutId);
        if (view == null) return;

        TextView tv = view.findViewById(textId);
        if (tv != null) {
            tv.setText(resId);
        }
        show(view, Toast.LENGTH_SHORT);
    }

    /**
     * 安全地显示长时自定义吐司
     */
    public static void showCustomLong(@LayoutRes final int layoutId, @IdRes final int textId, String msg) {
        View view = getView(layoutId);
        if (view == null) return;

        TextView tv = view.findViewById(textId);
        if (tv != null) {
            tv.setText(msg);
            /**
             * 此处用于接口返回提示文字超长时 动态修改提示框的宽度 避免提示过于狭长难看
             */
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tv.getLayoutParams();
            if (msg.length() > 104) {
                params.width = DisplayUtils.dip2px(YehApp.getInstance(), 300f);
            } else {
                params.width = DisplayUtils.dip2px(YehApp.getInstance(), 160f);
            }
            tv.setLayoutParams(params);
        }

        show(view, Toast.LENGTH_LONG);
    }

    /**
     * 安全地显示长时自定义吐司
     */
    public static void showCustomLong(@LayoutRes final int layoutId, @IdRes final int textId, @StringRes final int resId) {
        View view = getView(layoutId);
        if (view == null) return;

        TextView tv = view.findViewById(textId);
        if (tv != null) {
            tv.setText(resId);
        }
        show(view, Toast.LENGTH_LONG);
    }

    /**
     * 取消吐司显示
     */
    public static void cancel() {
        if (sToast != null) {
            sToast.cancel();
            sToast = null;
        }
    }

    private static void show(@StringRes final int resId, final int duration) {
        show(getContext().getResources().getText(resId).toString(), duration);
    }

    private static void show(@StringRes final int resId, final int duration, final Object... args) {
        show(String.format(getContext().getResources().getString(resId), args), duration);
    }

    private static void show(final String format, final int duration, final Object... args) {
        show(String.format(format, args), duration);
    }

    private static void show(final CharSequence text, final int duration) {
        HANDLER.post(() -> {
            cancel();
            sToast = Toast.makeText(getContext(), text, duration);
            // solve the font of toast
            TextView tvMessage = sToast.getView().findViewById(android.R.id.message);
            TextViewCompat.setTextAppearance(tvMessage, android.R.style.TextAppearance);
            tvMessage.setTextColor(msgColor);
            sToast.setGravity(gravity, xOffset, yOffset);
            setBg(tvMessage);
            sToast.show();
        });
    }

    private static void show(final View view, final int duration) {
        HANDLER.post(() -> {
            cancel();
            sToast = new Toast(getContext());
            sToast.setView(view);
            sToast.setDuration(duration);
            sToast.setGravity(gravity, xOffset, yOffset);
            setBg();
            sToast.show();
        });
    }

    private static void setBg() {
        View toastView = sToast.getView();
        if (bgResource != -1) {
            toastView.setBackgroundResource(bgResource);
        } else if (bgColor != COLOR_DEFAULT) {
            Drawable background = toastView.getBackground();
            if (background != null) {
                background.setColorFilter(
                        new PorterDuffColorFilter(bgColor, PorterDuff.Mode.SRC_IN)
                );
            } else {
                ViewCompat.setBackground(toastView, new ColorDrawable(bgColor));
            }
        }
    }

    private static void setBg(final TextView tvMsg) {
        View toastView = sToast.getView();
        if (bgResource != -1) {
            toastView.setBackgroundResource(bgResource);
            tvMsg.setBackgroundColor(Color.TRANSPARENT);
        } else if (bgColor != COLOR_DEFAULT) {
            Drawable tvBg = toastView.getBackground();
            Drawable msgBg = tvMsg.getBackground();
            if (tvBg != null && msgBg != null) {
                tvBg.setColorFilter(new PorterDuffColorFilter(bgColor, PorterDuff.Mode.SRC_IN));
                tvMsg.setBackgroundColor(Color.TRANSPARENT);
            } else if (tvBg != null) {
                tvBg.setColorFilter(new PorterDuffColorFilter(bgColor, PorterDuff.Mode.SRC_IN));
            } else if (msgBg != null) {
                msgBg.setColorFilter(new PorterDuffColorFilter(bgColor, PorterDuff.Mode.SRC_IN));
            } else {
                toastView.setBackgroundColor(bgColor);
            }
        }
    }

    private static View getView(@LayoutRes final int layoutId) {
        LayoutInflater inflate =
                (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        return inflate != null ? inflate.inflate(layoutId, null) : null;
    }

    /**
     * 多语言情况下 应用不重启 Application的Context不会立马切换语言
     * 所以优先使用Activity的Context 保证切换多语言后Toast的多语言立马生效
     *
     * @return Context
     */
    private static Context getContext() {
        return ActivityUtils.getTopActivity() == null ? YehApp.getInstance() : ActivityUtils.getTopActivity();
    }
}
